package com.cloudweb.oa.controller;

import cn.js.fan.db.ListResult;
import cn.js.fan.db.SQLFilter;
import cn.js.fan.util.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.service.IFileService;
import com.cloudweb.oa.utils.ResponseUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.flow.DocTemplateMgr;
import com.redmoon.oa.person.UserDb;
import com.redmoon.oa.person.UserMgr;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.pvg.RoleDb;
import com.redmoon.oa.pvg.RoleMgr;
import com.redmoon.oa.stamp.StampDb;
import com.redmoon.oa.stamp.StampLogDb;
import com.redmoon.oa.stamp.StampMgr;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Vector;

@Api(tags = "印章")
@Controller
@RequestMapping("/stamp")
public class StampController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ResponseUtil responseUtil;

    @ApiOperation(value = "印章列表", notes = "印章列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "年份", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "年份", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page, @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        String by = ParamUtil.get(request, "by");
        if ("".equals(by)) {
            by = "name";
        }
        String what = ParamUtil.get(request, "what");

        StampDb ld = new StampDb();
        String kind = StampDb.KIND_DEFAULT;

        String sql = ld.getListSql(kind);

        if (!"".equals(what)) {
            if ("name".equals(by)) {
                sql = "select id from " + ld.getTableName() + " where kind=" + StrUtil.sqlstr(kind) + " and title like " + StrUtil.sqlstr("%" + what + "%") + " order by sort";
            }
        }

        JSONArray ary = new JSONArray();
        UserMgr um = new UserMgr();
        RoleMgr rm = new RoleMgr();
        ListResult lr = ld.listResult(sql, page, pageSize);
        Vector v = lr.getResult();
        int i = 100;
        for (Object o : v) {
            ld = (StampDb)o;

            i++;
            String userNames = "";
            String userRealNames = "";
            String[] aryusers = StrUtil.split(ld.getUserNames(), ",");
            if (aryusers != null) {
                for (String aryuser : aryusers) {
                    UserDb ud = um.getUserDb(aryuser);
                    if (!ud.isLoaded()) {
                        continue;
                    }
                    if ("".equals(userNames)) {
                        userNames = aryuser;
                        userRealNames = ud.getRealName();
                    } else {
                        userNames += "," + aryuser;
                        userRealNames += "," + ud.getRealName();
                    }
                }
            }

            String roleCodes = "";
            String roleNames = "";
            String[] aryRoles = StrUtil.split(ld.getRoleCodes(), ",");
            if (aryRoles != null) {
                for (String aryRole : aryRoles) {
                    RoleDb rd = rm.getRoleDb(aryRole);
                    if (!rd.isLoaded()) {
                        continue;
                    }
                    if ("".equals(roleCodes)) {
                        roleCodes = aryRole;
                        roleNames = rd.getDesc();
                    } else {
                        roleCodes += "," + aryRole;
                        roleNames += "," + rd.getDesc();
                    }
                }
            }

            String imgPath = ld.getImageUrl();

            JSONObject json = new JSONObject();
            json.put("imgPath", imgPath);
            json.put("roleCodes", roleCodes);
            json.put("roleNames", roleNames);
            json.put("userNames", userNames);
            json.put("userRealNames", userRealNames);
            json.put("pwd", ld.getPwd());
            json.put("id", ld.getId());
            json.put("kind", ld.getKind());
            json.put("title", ld.getTitle());
            ary.add(json);
        }

        long total = lr.getTotal();
        JSONObject json = new JSONObject();
        json.put("total", total);
        json.put("list", ary);
        return new Result<>(json);
    }

    @ApiOperation(value = "删除印章", notes = "删除印章", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> del() {
        boolean re;
        try {
            StampMgr lm = new StampMgr();
            ServletContext application = request.getSession().getServletContext();
            re = lm.del(application, request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "创建印章", notes = "创建印章", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> create() {
        boolean re;
        try {
            StampMgr lm = new StampMgr();
            ServletContext application = request.getSession().getServletContext();
            re = lm.add(application, request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "修改印章", notes = "修改印章", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> update() {
        boolean re;
        try {
            StampMgr lm = new StampMgr();
            ServletContext application = request.getSession().getServletContext();
            re = lm.modify(application, request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "印章日志列表", notes = "印章日志列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "年份", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "年份", required = false, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/listLog", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listLog(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page, @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        StampLogDb ld = new StampLogDb();
        String sql = "select id from oa_stamp_log where 1=1 ";

        String userName = ParamUtil.get(request, "userName");
        String beginDate = ParamUtil.get(request, "beginDate");
        String endDate = ParamUtil.get(request, "endDate");
        String stampId = ParamUtil.get(request, "stampId");

        String op = ParamUtil.get(request, "op");
        if ("search".equals(op)) {
            String cond = "";
            if (!"".equals(userName)) {
                sql = "select s.id from oa_stamp_log s, users u where u.name=s.user_name ";
                cond = " and u.realName like " + StrUtil.sqlstr("%" + userName + "%");
            }
            if (!"".equals(beginDate)) {
                cond += " and create_date>=" + SQLFilter.getDateStr(beginDate, "yyyy-MM-dd");
            }
            if (!"".equals(endDate)) {
                cond += " and create_date<=" + SQLFilter.getDateStr(endDate, "yyyy-MM-dd");
            }
            if (!"".equals(stampId)) {
                cond += " and stamp_id=" + stampId;
            }
            if (!"".equals(cond)) {
                sql += cond;
            }
        }

        sql += " order by id desc";

        // System.out.println(sql);

        JSONArray ary = new JSONArray();
        StampDb sd = new StampDb();
        ListResult lr = null;
        try {
            lr = ld.listResult(sql, page, pageSize);
            Vector v = lr.getResult();
            UserMgr um = new UserMgr();
            for (Object o : v) {
                ld = (StampLogDb)o;
                UserDb ud = um.getUserDb(ld.getString("user_name"));
                sd = sd.getStampDb(ld.getInt("stamp_id"));

                JSONObject json = new JSONObject();
                json.put("createDate", DateUtil.format(ld.getDate("create_date"), "yyyy-MM-dd HH:mm:ss"));
                json.put("realName", ud.getRealName());
                json.put("ip", ld.getString("ip"));
                json.put("title", sd.getTitle());
                json.put("id", ld.getLong("id"));
                ary.add(json);
            }
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e.getMessage(request));
        }

        long total = lr.getTotal();
        JSONObject json = new JSONObject();
        json.put("total", total);
        json.put("list", ary);
        return new Result<>(json);
    }

    @ApiOperation(value = "删除印章日志", notes = "删除印章日志", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID，以逗号分隔", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/delLog", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> delLog(@RequestParam(value = "ids") String strIds) {
        boolean re = true;
        try {
            StampLogDb ld = new StampLogDb();
            String[] ids = StrUtil.split(strIds, ",");
            if (ids!=null) {
                for (String id : ids) {
                    StampLogDb ldb = ld.getStampLogDb(StrUtil.toInt(id));
                    re = ldb.del();
                }
            }
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "取得全部印章", notes = "取得全部印章", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin', 'admin.unit')")
    @ResponseBody
    @RequestMapping(value = "/getAllStamp", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> getAllStamp() {
        JSONArray ary = new JSONArray();
        StampDb sd = new StampDb();
        String sql = sd.getListSql(StampDb.KIND_DEFAULT);
        for (Object o : sd.list(sql)) {
            sd = (StampDb) o;
            JSONObject json = new JSONObject();
            json.put("id", sd.getId());
            json.put("title", sd.getTitle());
            ary.add(json);
        }
        return new Result<>(ary);
    }
}
